package com.elong.businesstravel.modules.orders;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

import com.android.support.jhf.debug.DebugLog;
import com.android.support.jhf.dialog.CustomWaitDialog.OnKeyCancel;
import com.android.support.jhf.handlerui.HandlerPostUI;
import com.android.support.jhf.handlerui.HandlerToastUI;
import com.android.support.jhf.network.BaseErrorListener;
import com.android.support.jhf.network.BaseStateListener;
import com.android.support.jhf.network.ErrorExceptionHandler;
import com.android.support.jhf.network.IStateListener;
import com.android.support.jhf.network.NetworkClient;
import com.android.support.jhf.network.loopj.android.http.AsyncHttpRequest;
import com.android.support.jhf.network.loopj.android.http.ResponseHandlerInterface;
import com.android.support.jhf.utils.Base64Util;
import com.android.support.jhf.utils.MobileUtils;
import com.android.support.jhf.viewpagercanscroll.CanScrollViewPager;
import com.elong.businesstravel.R;
import com.elong.businesstravel.base.Constant;
import com.elong.businesstravel.base.baseactivity.BaseActivity;
import com.elong.businesstravel.base.dialog.CustomAlertDialog;
import com.elong.businesstravel.base.recorder.BaseRecordActivity;
import com.elong.businesstravel.base.recorder.Recorder;
import com.elong.businesstravel.base.view.TitleNavBarView;
import com.elong.businesstravel.entitys.OrderInfo;
import com.elong.businesstravel.modules.home.HomeActivity;
import com.elong.businesstravel.modules.home.NewHomeActivity;
import com.elong.businesstravel.modules.orders.adapter.OrdersPagerAdapter;
import com.elong.businesstravel.modules.orders.view.OrdersView;
import com.elong.businesstravel.protocol.ProtocolDef;
import com.elong.businesstravel.protocol.order.AddcltreviewRequest;
import com.elong.businesstravel.protocol.order.AddcltreviewResponse;
import com.elong.businesstravel.protocol.order.GetMemberOrderRequest;
import com.elong.businesstravel.protocol.order.GetMemberOrderResponse;

/**
 * 我的订单
 * 
 * @author lenovo
 * 
 */
public class OrdersActivity extends BaseActivity {

	private CanScrollViewPager mViewPager;
	private OrdersPagerAdapter mOrdersPagerAdapter;
	private TitleNavBarView mTitleNavBarView;

	private int mPage = 1;
	private int mCount = 0;
	private List<OrderInfo> mOrderInfos = new ArrayList<OrderInfo>();
	private Recorder mRecorder;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_orders);

		init();
	}

	@Override
	protected void init() {

		setTitleNavBar();

		mRecorder = new Recorder();
		mViewPager = (CanScrollViewPager) findViewById(R.id.viewPager);
		mOrdersPagerAdapter = new OrdersPagerAdapter(mContext, mOrderInfos,
				mViewPager, mRecorder);
		mViewPager.setAdapter(mOrdersPagerAdapter);

		setListener();

		getMemberOrder(false);
	}

	@Override
	protected void setListener() {
		mViewPager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int arg0) {
				mTitleNavBarView.setMessage("订单（" + (arg0 + 1) + "/" + mCount
						+ "）");
				if (arg0 + 1 == mOrderInfos.size()) {
					getMemberOrder(true);
				}

			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {

			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
				// 状态有三个0空闲，1是增在滑行中，2目标加载完毕
				/**
				 * Indicates that the pager is in an idle, settled state. The
				 * current page is fully in view and no animation is in
				 * progress.
				 */
				// public static final int SCROLL_STATE_IDLE = 0;
				/**
				 * Indicates that the pager is currently being dragged by the
				 * user.
				 */
				// public static final int SCROLL_STATE_DRAGGING = 1;
				/**
				 * Indicates that the pager is in the process of settling to a
				 * final position.
				 */
				// public static final int SCROLL_STATE_SETTLING = 2;

				if (arg0 == ViewPager.SCROLL_STATE_DRAGGING) {
					if (Recorder.PLAYING_STATE == mRecorder.getState()) {
						mRecorder.stopPlayback();
						mOrdersPagerAdapter.stopRecorderAnim();
						mViewPager.setCanScroll(true);
					} else {
					}
				}

			}
		});
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (null != mOrdersPagerAdapter)
			mOrdersPagerAdapter.stopPlayback();

	}

	@Override
	protected void setTitleNavBar() {

		mTitleNavBarView = (TitleNavBarView) findViewById(R.id.titleNavBarView);
		mTitleNavBarView.setMessage("订单（0/0）");
		mTitleNavBarView.setLeftDrawableImage(R.drawable.btn_title_back);
		mTitleNavBarView.setLeftButtonImageString(0, "返回", R.color.text_blue);
		mTitleNavBarView.setLeftButtonOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				quit();
			}
		});
		mTitleNavBarView.setRightImageView(R.drawable.ic_phone,
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						// call phone

						final CustomAlertDialog customAlertDialog = new CustomAlertDialog(
								mContext, R.style.CustomAlertDialog);
						customAlertDialog
								.setMessage(Constant.ELONG_CUSTOMER_SERVICE_PHONE);
						customAlertDialog.setLeftButton("拨打",
								new OnClickListener() {

									@Override
									public void onClick(View arg0) {
										MobileUtils
												.callPhoneActivity(
														mContext,
														Constant.ELONG_CUSTOMER_SERVICE_PHONE,
														Intent.ACTION_VIEW);
									}
								});
						customAlertDialog.setRightButton("取消",
								new OnClickListener() {

									@Override
									public void onClick(View arg0) {

									}
								});
						customAlertDialog.show();
					}
				});
	}

	private void getMemberOrder(final boolean moreFlag) {

		if (moreFlag) {
			mPage++;
		} else {
			mPage = 1;
		}

		NetworkClient.getNetworkClient().PostRequest(
				new GetMemberOrderRequest(mContext, mPage + ""),
				new GetMemberOrderResponse() {
					@Override
					public void onResponse(
							ResponseHandlerInterface responseHandlerInterface) {
						HandlerPostUI.getHandlerPostUI(new Runnable() {

							@Override
							public void run() {
								mCount = count;
								if (moreFlag) {
									// 更多
									mOrderInfos.addAll(orderInfos);
									mTitleNavBarView.setMessage("订单（"
											+ (mViewPager.getCurrentItem() + 1)
											+ "/" + mCount + "）");
									mOrdersPagerAdapter.notifyDataSetChanged();
								} else {
									// 刷新
									mOrderInfos.clear();
									mOrderInfos.addAll(orderInfos);
									mTitleNavBarView.setMessage("订单（1/"
											+ mCount + "）");
									mOrdersPagerAdapter.notifyDataSetChanged();
								}

							}
						});
					}
				}, null, new BaseErrorListener() {
				});
	}

	private void quit() {
//		Intent intent = new Intent(mContext, HomeActivity.class);
		Intent intent = new Intent(mContext, NewHomeActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(intent);
		finish();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK) {
			quit();
			return true;
		}

		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case 0: {
			// 发送音频返回
			switch (resultCode) {
			case RESULT_OK: {
				if (null != data) {
					String voiceUrl = data.getStringExtra("voiceUrl");
					String voiceLenght = data.getStringExtra("voiceLenght");
					if (!TextUtils.isEmpty(voiceUrl)) {
						// 刷新界面，评论成功
						OrderInfo orderInfo = mOrderInfos.get(mViewPager
								.getCurrentItem());
						orderInfo.voicetime = voiceLenght;
						orderInfo.voiceurl = voiceUrl;
						orderInfo.isvoice = "1";
						mOrdersPagerAdapter.notifyDataSetChanged();
					}
				}
				break;
			}
			case RESULT_CANCELED: {

				break;
			}
			default:
				break;
			}
			break;
		}
		default:
			break;
		}
	}

}
